package com.rd.server.modules.user.service;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.alibaba.fastjson2.JSONObject;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.rd.common.exception.BusinessException;
import com.rd.common.model.ResultCode;
import com.rd.server.modules.user.mapper.UserMapper;
import com.rd.server.modules.user.model.po.UserPO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author zyy
 * @Date 2025/2/13 9:31
 * @Version 1.0
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements UserService {

    /**
     * 新建FIFOCache
     */
    Cache<String, String> cache = CacheUtil.newFIFOCache(3);

    public static final String USER_CACHE_NAME = "userCache";

    @Override
    public void pageList() {

    }

    @Override
    public UserPO selectByOpenId(String openId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("open_id", openId);
        return this.getOne(queryWrapper);
    }

    @Override
    public UserPO selectByUserId(String userId) {
        String userJsonStr = cache.get(USER_CACHE_NAME + userId);
        if (StringUtils.isNoneBlank(userJsonStr)) {
            return JSONObject.parseObject(userJsonStr,UserPO.class);
        }
        UserPO userPO = this.getById(userId);
        if (userPO == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        cache.put(USER_CACHE_NAME + userId,JSONObject.toJSONString(userPO));
        return userPO;
    }
}
